package com.fengye.common.utils;

import com.fengye.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * @author sunlei
 * @version 1.0
 * @date 2024/6/25 15:06:19
 * @description 国际化工具类
 */
public class I18nUtil {

    private static final Logger logger = LoggerFactory.getLogger(I18nUtil.class);
    private static final MessageSource messageSource = SpringUtils.getBean(MessageSource.class);

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        if (code == null || code.isEmpty()) {
            logger.warn("Message key is null or empty.");
            return "未知消息";
        }

        try {
            return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            logger.error("Failed to get message for key: {}", code, e);
            return "未知消息";
        }
    }
}
